package com.weayer.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.weayer.constant.CommonStatusEnum;
import com.weayer.dto.PassengerUser;
import com.weayer.dto.ResponseResult;
import com.weayer.mapper.PassengerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: Service服务 - 鉴权 - 用户service
 * @author: Weayer
 **/
@Service
public class UserService {
    @Autowired
    private PassengerMapper passengerUserMapper;

    /**
     * @Description: 手机号登录 or 注册
     * @Param: [passengerPhone]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult loginOrRegister(String passengerPhone){
        // 根据手机号查询用户
        Map<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone );
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
        // 判断用户是否存在，若不存在则插入用户，存在则更新时间
        PassengerUser passengerUser = new PassengerUser();
        LocalDateTime now = LocalDateTime.now();
        passengerUser.setGmtModified(now);
        if(passengerUsers.size() == 0){
            passengerUser.setPassengerName("honey");
            passengerUser.setPassengerGender((byte)1);
            passengerUser.setPassengerPhone(passengerPhone);
            passengerUser.setState((byte)0);
            passengerUser.setGmtCreate(now);
            passengerUserMapper.insert(passengerUser);
        }else{
            LambdaUpdateWrapper<PassengerUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(PassengerUser::getPassengerPhone, passengerPhone).set(PassengerUser::getGmtModified, now);
            passengerUserMapper.update(null, lambdaUpdateWrapper);
        }
        return ResponseResult.success(passengerUsers);
    }
    /**
     * @Description: 手机号查询用户信息
     * @Param: [passengerPhone]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult getUserByPhone(String passengerPhone){
        // 根据手机号查询用户
        Map<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone );
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
        // 判断用户是否存在，若不存在则返回错误，存在则返回用户信息
        if(passengerUsers.size() == 0){
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(), CommonStatusEnum.USER_NOT_EXIST.getValue());
        }else{
            return ResponseResult.success(passengerUsers.get(0));
        }
    }
}
